package com.zhilehuo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.github.pagehelper.PageInfo;
import com.zhilehuo.common.BaseResponse;
import com.zhilehuo.model.po.Paragraph;
import com.zhilehuo.model.vo.ParagraphVO;
import com.zhilehuo.service.IParagraphService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/paragraph")
@CrossOrigin(origins = "*")
public class ParagraphController {

    private static final String filePath = System.getProperty("user.dir") + "/files/";

    @Value("${server.port:8081}")
    private String port;

    @Value("${ip:localhost}")
    private String ip;
    @Resource
    private IParagraphService paragraphService;


    /**
     * 更新字体
     * @param font
     * @param paragraphId
     * @return
     */
    @GetMapping("/updateFont")
    public BaseResponse<String> updateFont(
            @RequestParam("font") Integer font,
            @RequestParam("paragraphId") Integer paragraphId) {
        if (font == null || paragraphId == null) {
            return new BaseResponse<>(500, "请求参数错误");
        }
        return paragraphService.updateFont(font, paragraphId);
    }


    @RequestMapping(value = "/page/{articleID}", method = RequestMethod.GET)
    public BaseResponse<PageInfo<ParagraphVO>> getArticlePronunciation(@PathVariable Integer articleID ,@RequestParam(defaultValue = "1") Integer pageNum,
                                                                       @RequestParam(defaultValue = "10") Integer pageSize) {

        if (articleID == null) {
            return new BaseResponse<>(400, null);
        }

        // 从 Service 获取数据
        PageInfo<ParagraphVO> pageInfo = paragraphService.getParagraphsByArticleId(articleID,pageNum,pageSize);

        // 返回标准响应
        return new BaseResponse<>(200, pageInfo);
    }


    @PostMapping("/updateImage")
    public BaseResponse<Map<String, String>> uploadParagraphImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam("paragraphId") Integer paragraphId) {

        String flag;
        synchronized (FileController.class) {
            flag = System.currentTimeMillis() + "";
            ThreadUtil.sleep(1L);
        }

        String fileName = file.getOriginalFilename();
        try {
            if (!FileUtil.isDirectory(filePath)) {
                FileUtil.mkdir(filePath);
            }

            // 文件存储形式：时间戳-文件名
            String storedFileName = flag + "-" + fileName;
            FileUtil.writeBytes(file.getBytes(), filePath + storedFileName);

            // 构建图片URL
            String imageUrl = "http://" + ip + ":" + port + "/files/" + storedFileName;

            // 更新数据库中的image_url字段
            Paragraph paragraph = new Paragraph();
            paragraph.setId(paragraphId);
            paragraph.setImageUrl(imageUrl);
            paragraphService.updateByPrimaryKeySelective(paragraph);  //http://localhost:8081/files/1743152101636-f1lj5pww4yo.jpg

            // 返回图片URL
            Map<String, String> result = new HashMap<>();
            result.put("imageUrl", imageUrl);

            return new BaseResponse<>(200, result,"上传成功" );

        } catch (Exception e) {
            System.err.println(fileName + "--文件上传失败");
            return new BaseResponse<>(500, null,"文件上传失败");
        }
    }
}
